import { Context } from 'koa';
import { Logger } from '../utils/logger';
import { ResponseUtil } from '../utils/response';
import { AppError } from '../utils/errors';

const logger = Logger.getInstance();

export const errorHandler = async (ctx: Context, next: () => Promise<void>) => {
  try {
    await next();
  } catch (err: any) {
    const error = err as AppError;

    // 记录错误日志
    logger.error('Error occurred:', {
      message: error.message,
      stack: error.stack,
      url: ctx.url,
      method: ctx.method,
      ip: ctx.ip,
      userAgent: ctx.headers['user-agent']
    });

    // 处理特定类型的错误
    let statusCode = error.statusCode || 500;
    let message = error.message || '服务器内部错误';
    let code = error.code || 'INTERNAL_ERROR';

    // 处理验证错误
    if (error.name === 'ValidationError') {
      statusCode = 400;
      message = '输入数据验证失败';
      code = 'VALIDATION_ERROR';
    }

    // 处理JWT错误
    if (error.name === 'JsonWebTokenError') {
      statusCode = 401;
      message = '无效的令牌';
      code = 'INVALID_TOKEN';
    }

    // 处理JWT过期错误
    if (error.name === 'TokenExpiredError') {
      statusCode = 401;
      message = '令牌已过期';
      code = 'TOKEN_EXPIRED';
    }

    // 设置响应状态和内容
    ctx.status = statusCode;
    ctx.body = ResponseUtil.error(ctx, message, code, statusCode);

    // 开发环境返回详细错误信息
    if (process.env.NODE_ENV === 'development') {
      (ctx.body as any).stack = error.stack;
    }
  }
};

/**
 * 404错误处理中间件
 */
export const notFoundHandler = async (ctx: Context) => {
  ctx.status = 404;
  ctx.body = ResponseUtil.error(ctx, `路径 ${ctx.url} 不存在`, 'NOT_FOUND', 404);
};